package io.github.wslxm.springbootplus2.utils;


import io.github.wslxm.springbootplus2.core.utils.bean.XjSpringContextUtil;
import io.github.wslxm.springbootplus2.core.utils.validated.XjValidUtil;
import io.github.wslxm.springbootplus2.starter.redis.util.RedisUtil;

import java.time.temporal.ChronoUnit;

/**
 * 限流工具内
 *
 * @author 王松
 * @mail 1720696548@qq.com
 * @date 2025/8/26 17:08
 */
public class XjLimitUtil {

    private static RedisUtil redisUtil = null;

    private static void init() {
        if (redisUtil == null) {
            redisUtil = (RedisUtil) XjSpringContextUtil.getBean("redisUtil");
        }
    }

    /**
     * 限流方法
     *
     * @param key      限流 key
     * @param qps      限流 qbs
     * @param timeUnit 时间类型
     * @param errorMsg 触发限流时的错误消息
     */
    public static void limit(String key, Integer qps, ChronoUnit timeUnit, String errorMsg) {
        init();
        // 验证限流 (key 存在并且自增值大于等于 qps 表示被限流)
        if (redisUtil.hasKey(key)) {
            Integer value = (Integer) redisUtil.get(key);
            XjValidUtil.isTrue(value != null && value >= qps, errorMsg);
            redisUtil.increment(key, 1);
        } else {
            redisUtil.increment(key, 1);
            long extTime = timeUnit.getDuration().getSeconds();
            redisUtil.expire(key, extTime);
        }
    }
}
